<template>
  <div class="bar-chart" ref="chart" :style="{ width: width, height: height }"></div>
</template>

<script>
import * as echarts from 'echarts'
import { debounce } from 'lodash'

export default {
  name: 'BarChart',
  props: {
    chartData: {
      type: Object,
      required: true
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    color: {
      type: Array,
      default: () => ['#5470C6', '#91CC75', '#EE6666']
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.updateChart()
      }
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.updateChart()
    },
    updateChart() {
      if (!this.chartData || !this.chartData.xAxis || !this.chartData.series) {
        return
      }

      const option = {
        color: this.color,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: this.chartData.series.map(item => item.name),
          right: 10,
          top: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.chartData.xAxis,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisLabel: {
            color: '#666',
            rotate: 30, // 旋转角度
            interval: 0, // 强制显示所有标签
            margin: 10 // 标签与轴线距离
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#666',
            formatter: '{value}%'
          },
          splitLine: {
            lineStyle: {
              color: '#eee'
            }
          }
        },
        series: this.chartData.series.map(item => ({
          ...item,
          type: 'bar',
          barWidth: '40%',
          emphasis: {
            focus: 'series'
          }
        }))
      }

      this.chart.setOption(option)
    },
    handleResize: debounce(function() {
      if (this.chart) {
        this.chart.resize()
      }
    }, 300)
  }
}
</script>

<style scoped>
.bar-chart {
  width: 100%;
  height: 100%;
}
</style>
